const express=require('express')
const pool=require('../pool')
const router=express.Router()
// 注册
router.post('/register',(req,res,next)=>{
	let obj=req.body
	let userName=obj.userName
	//console.log(obj)
	if(!userName){
		res.send({code:401,msg:'用户名不能为空'})
		return
	}
	pool.query('select userId from user where userName =?',[userName],(err,r)=>{
		if(err){
			return next(err)
		}
		if(r.length){
			res.send({code:402,msg:'用户名已存在',data:r})
			return
		}
	})
	pool.query('insert into user set ?',[obj],(err,r)=>{
		if(err){
			return next(err)
		}
		res.send({code:200,msg:'注册成功',data:r})
	})
})

// 登录
router.post('/login',(req,res,next)=>{
	let obj=req.body
	let userName=obj.userName.trim()
	let upwd=obj.upwd.trim()
	if(!userName){
		res.send({code:401,msg:'用户名不能为空'})
		return
	}
	if(!upwd){
		res.send({code:402,msg:'密码不能为空'})
		return
	}
	pool.query('select userId from user where userName=? and upwd=?',[userName,upwd],(err,r)=>{
		if(err){
			return next(err)
		}
		if(!r.length){
			res.send({code:401,msg:'用户名或密码错误',data:r})
			return
		}
		res.send({code:200,msg:'登录成功',data:r})
	})
	
})
// 模糊查询搜索
router.get('/queryLike',(req,res,next)=>{
	let obj=req.query
	let name1=obj.userName
	
	pool.query('select * from user where userName like "%'+name1+'%" ',(err,r)=>{
		if(err){
			return next(err)
		}
		if(r.length){
			res.send({code:200,msg:'搜索成功',data:r})
		}else{
			res.send({code:404,msg:'查无此用户',data:r})
		}
		
	})
})

// 通过用户名查找用户信息
router.get('/queryByName',(req,res,next)=>{
	let obj=req.query
	let name1=obj.userName
	
	pool.query('select * from user where userName =?',[name1],(err,r)=>{
		if(err){
			return next(err)
		}
		if(r.length){
			res.send({code:200,msg:'搜索成功',data:r})
		}else{
			res.send({code:404,msg:'查无此用户',data:r})
		}
		
	})
})

// 查询所有
router.get('/queryAll',(req,res,next)=>{
	pool.query('select * from user',(err,r)=>{
		if(err){
			return next(err)
		}
		res.send({code:200,msg:'查找所有用户成功',data:r})
	})
})

// 删除
router.get('/delete',(req,res,next)=>{
	let obj=req.query
	
	pool.query('delete from user where userId=?',[obj.userId],(err,r)=>{
		if(err){
			return next(err)
		}
		res.send({code:200,msg:'删除用户成功',data:r})
	})
})

// 修改
router.post('/modify',(req,res,next)=>{
	let obj=req.body
	pool.query('update user set ? where userId=?',[obj,obj.userId],(err,r)=>{
		if(err){
			return next(err)
		}
		res.send({code:200,msg:'修改用户成功',data:r})
	})
})
module.exports=router